package tech.heptagram.staff.service.impl;

import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import tech.heptagram.staff.domain.StaffUser;
import tech.heptagram.staff.mapper.StaffUserMapper;
import tech.heptagram.staff.service.StaffUserService;

/**
 * @author wang.yuchuan
 * @date 2018/9/5
 */
@Service
@Slf4j
public class StaffUserServiceImpl implements StaffUserService {

    @Value("${staff.default.salt}")
    private String defaultSalt;
    @Value("${staff.default.password}")
    private String defaultPassword;

    @Resource
    private StaffUserMapper staffUserMapper;

    @Override
    public boolean auth(String staffCode, String password) {
        StaffUser staffUser = staffUserMapper.selectByStaffCode(staffCode);

        // 把输入的密码加密
        String inputEncodePassword = encodePassword(password, staffUser.getSalt());
        if(inputEncodePassword.equals(staffUser.getPassword())){
            return true;
        }
        return false;
    }

    @Override
    public String saveStaffUser(StaffUser staffUser) {
        staffUser.setSalt(defaultSalt);
        staffUser.setPassword(encodePassword(defaultPassword,defaultSalt));
        staffUserMapper.insertStaffUser(staffUser);
        return staffUser.getStaffCode();
    }

    private static String encodePassword(String password, String salt) {
        Sha256Hash sha256Hash = new Sha256Hash(password, salt);
        return Hex.encodeToString(sha256Hash.getBytes());
    }
}
